/*
 * mnm.c
 *
 *  Created on: Apr 25, 2013
 *      Author: Daniel
 */

#include "DSP28x_Project.h"
#include "mnm.h"

typedef char byte;

void InitMNM(void) {
	InitMNM_Offsets();
	InitMNM_CTRL_REGS();
}

void InitMNM_Offsets(void) {

	I2caRegs.I2CSTR.all = I2C_CLR_NACK_BIT;		// clear the NACK bit
	while(I2caRegs.I2CSTR.bit.BB == 1);			// wait until the bus is no longer busy
	I2caRegs.I2CSAR = MNM_I2C_Address;			// tell the I2C peripheral where we're transmitting
	I2caRegs.I2CCNT = MNM_NUMBYTES_OFFSETS;		// tell the I2C peripheral how many bytes we're transmitting

	I2caRegs.I2CDXR = MNM_ADDR_OFF_X_MSB;		// send the address of the first register
	I2caRegs.I2CDXR = MNM_INIT_OFF_X_MSB;		// each of these bytes is written in sequence
	I2caRegs.I2CDXR = MNM_INIT_OFF_X_LSB;		// starting at the register address (first byte sent)
	I2caRegs.I2CDXR = MNM_INIT_OFF_Y_MSB;
	I2caRegs.I2CDXR = MNM_INIT_OFF_Y_LSB;
	I2caRegs.I2CDXR = MNM_INIT_OFF_Z_MSB;
	I2caRegs.I2CDXR = MNM_INIT_OFF_Z_LSB;
}

void InitMNM_CTRL_REGS(void) {

	I2caRegs.I2CSTR.all = I2C_CLR_NACK_BIT;		// clear the NACK bit

	while(I2caRegs.I2CSTR.bit.BB == 1);			// wait until the bus is no longer busy

	I2caRegs.I2CSAR = MNM_I2C_Address;			// tell the I2C peripheral where we're transmitting
	I2caRegs.I2CCNT = MNM_NUMBYTES_CTRL_REGS;	// tell the I2C peripheral how many bytes we're transmitting

	I2caRegs.I2CDXR = MNM_ADDR_CTRL_REG1;		// send the address of the first register
	I2caRegs.I2CDXR = MNM_INIT_CTRL_REG1;		// each of these bytes is written in sequence
	I2caRegs.I2CDXR = MNM_INIT_CTRL_REG2;		// starting at the register address (first byte sent)

	return;
}

void MNM_read_all(Uint16 results[]) {

	byte temp;

	while(I2caRegs.I2CSTR.bit.BB == 1);
	I2caRegs.I2CSAR = MNM_I2C_Address;
	I2caRegs.I2CCNT = MNM_NUMBYTES_POLL;

	I2caRegs.I2CDXR = MNM_ADDR_OUT_X_MSB;

	I2caRegs.I2CMDR.all = 0x2620;				// issue a START command (no stop)

	while(I2caRegs.I2CSTR.bit.BB == 1);

	I2caRegs.I2CSAR = MNM_I2C_Address;
	I2caRegs.I2CCNT = MNM_NUMBYTES_READ_ALL;
	I2caRegs.I2CMDR.all = 0x2C20;				// issue a restart command

	while(I2caRegs.I2CSTR.bit.NACKSNT == 0);	// wait for the slave to finish transmitting

	temp = I2caRegs.I2CDRR << 8;				// x-axis magneto measurement
	results[0] = temp | I2caRegs.I2CDRR;

	temp = I2caRegs.I2CDRR << 8;				// y-axis magneto measurement
	results[1] = temp | I2caRegs.I2CDRR;

	temp = I2caRegs.I2CDRR << 8;				// z-axis magneto measurement
	results[2] = temp | I2caRegs.I2CDRR;

	return;
}
